// bind-phone.js
const app = getApp()

// 登录相关API配置
const LOGIN_BASE_URL = 'http://localhost:8082' // 后端服务地址

/**
 * 封装微信小程序的网络请求
 */
function request(options) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: LOGIN_BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      timeout: options.timeout || 10000,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(new Error(`请求失败: ${res.statusCode} - ${res.data?.message || '未知错误'}`))
        }
      },
      fail: (err) => {
        console.error('网络请求失败:', err)
        reject(new Error(`网络请求失败: ${err.errMsg || '连接超时'}`))
      }
    })
  })
}

/**
 * 登录相关API
 */
const loginApi = {
  // 发送验证码
  sendCode(phoneNumber) {
    return request({
      url: '/login/sendCode',
      method: 'POST',
      data: {
        phoneNumber: phoneNumber
      }
    })
  },

  // 绑定手机号
  bindPhone(token, phoneNumber, code) {
    return request({
      url: '/login/bindPhone',
      method: 'POST',
      data: {
        token: token,
        phoneNumber: phoneNumber,
        code: code
      }
    })
  }
}

Page({
  data: {
    phone: '',
    code: '',
    codeBtnText: '获取验证码',
    codeBtnDisabled: false,
    countdown: 0,
    isBinding: false
  },

  // 手机号输入
  onPhoneInput(e) {
    this.setData({
      phone: e.detail.value
    })
  },

  // 验证码输入
  onCodeInput(e) {
    this.setData({
      code: e.detail.value
    })
  },

  // 发送验证码
  async onSendCode() {
    const phone = this.data.phone
    if (!phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return
    }
    
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }

    try {
      wx.showLoading({
        title: '发送中...'
      })

      const result = await loginApi.sendCode(phone)
      
      wx.hideLoading()
      
      if (result.code === 200) {
        wx.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
        // 开始倒计时
        this.startCountdown()
      } else {
        wx.showToast({
          title: result.message || '发送失败',
          icon: 'none'
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('发送验证码失败:', error)
      wx.showToast({
        title: error.message || '发送失败，请重试',
        icon: 'none'
      })
    }
  },

  // 开始倒计时
  startCountdown() {
    let countdown = 60
    this.setData({
      codeBtnDisabled: true,
      codeBtnText: `${countdown}s后重发`,
      countdown: countdown
    })

    const timer = setInterval(() => {
      countdown--
      if (countdown <= 0) {
        clearInterval(timer)
        this.setData({
          codeBtnDisabled: false,
          codeBtnText: '获取验证码',
          countdown: 0
        })
      } else {
        this.setData({
          codeBtnText: `${countdown}s后重发`,
          countdown: countdown
        })
      }
    }, 1000)
  },

  // 绑定手机号
  async onBindPhone() {
    const { phone, code, isBinding } = this.data
    
    if (isBinding) return
    
    if (!phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    if (!code) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none',
        duration: 2000
      })
      return
    }

    // 设置绑定状态
    this.setData({
      isBinding: true
    })

    // 显示加载动画
    wx.showLoading({
      title: '绑定中...',
      mask: true
    })

    try {
      // 获取Token
      const token = wx.getStorageSync('token')
      if (!token) {
        throw new Error('请先登录')
      }

      const result = await loginApi.bindPhone(token, phone, code)
      
      wx.hideLoading()
      
      if (result.code === 200) {
        // 绑定成功动画
        wx.showToast({
          title: '绑定成功',
          icon: 'success',
          duration: 1500
        })
        
        // 更新全局用户信息
        const { userInfo } = result.data
        app.setUserInfo(userInfo)
        
        // 延迟返回，让用户看到成功提示
        setTimeout(() => {
          wx.navigateBack({
            success: () => {
              this.setData({
                isBinding: false
              })
            },
            fail: () => {
              this.setData({
                isBinding: false
              })
            }
          })
        }, 1500)
      } else {
        wx.showToast({
          title: result.message || '绑定失败',
          icon: 'none'
        })
        this.setData({
          isBinding: false
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('绑定手机号失败:', error)
      wx.showToast({
        title: error.message || '绑定失败，请重试',
        icon: 'none'
      })
      this.setData({
        isBinding: false
      })
    }
  },

  // 用户协议
  onAgreementTap() {
    wx.showToast({
      title: '用户协议',
      icon: 'none'
    })
  },

  // 隐私政策
  onPrivacyTap() {
    wx.showToast({
      title: '隐私政策',
      icon: 'none'
    })
  }
})

